<template>
  <div style="height: 100%">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :key="index" v-for="(item, index) in breadcrumbItems">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="table-wrap-box">
      <el-container>
        <el-aside class="side-wrap" width="220">
          <SideCategoryMenu :categoriesTree="busiFeatureTreeData" :first-default-checked="true"
            @add-btn-click="treeAddBtnClick" @del-btn-click="treeDelBtnClick" @edit-btn-click="treeEditBtnClick"
            @tree-node-click="treeNodeClickHandle" @tree-node-cancel-check="treeNodeCancelCheckHandler" />
        </el-aside>
        <el-main class="main-wrap">
          <div style="width: 160px;display: flex;justify-content: space-around;margin-bottom: 4px;">
            <el-button size="mini" @click="saveFeatureClick">
              <svg-icon class-name="svg-icon" icon-class="save"></svg-icon>
              保存
            </el-button>
            <el-button size="mini" icon="el-icon-plus" @click="addFeatureFieldClick">添加字段</el-button>
            <el-button size="mini" icon="el-icon-folder-add" @click="batchAddFeatureFieldClick">批量添加</el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="delFeatureClick">删除字段</el-button>
          </div>
          <el-tabs v-model="activeName" type="border-card" @tab-click="tabClickHandler">
            <el-tab-pane name="fieldList" label="字段列表" class="my-tab-panel">
              <el-table :data="featureFieldData" :max-height="430" border row-key="id" size="mini" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40">
                </el-table-column>
                <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                  align="center">
                  <template slot-scope="scope">
                    <span v-if="item.oper">
                      <el-button size="mini" type="text" @click="rowEditClick(scope.row)">编辑</el-button>
                      <el-button size="mini" type="text" style="color: #f56c6c"
                        @click="rowDelClick(scope.row)">删除</el-button>
                    </span>
                    <span v-else-if="item.prop === 'isRef'">
                      <span v-if="scope.row.isRef === 0">否</span>
                      <span v-if="scope.row.isRef === 1">是</span>
                    </span>
                    <template v-else-if="item.prop === 'typeId'">
                      <TreeSelect v-if="scope.row.editState" v-model="scope.row[item.prop]" :data="basicTypeData"
                        :props="{ label: 'text' }" label-key="name" node-key="name" size="mini" value-key="id">
                      </TreeSelect>
                      <span v-else>
                        {{ scope.row['typeLabel'] }}
                      </span>
                    </template>
                    <template v-else>
                      <template v-if="scope.row.editState">
                        <el-input size="mini" v-model="scope.row[item.prop]"></el-input>
                      </template>
                      <span v-else>
                        {{ scope.row[item.prop] }}
                      </span>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane name="objectInfo" label="对象信息">
              <h1>对象信息</h1>
            </el-tab-pane>
            <el-tab-pane name="sqlPreview" label="SQL预览">
              <el-input class="sql-textarea" type="textarea" :rows="18" v-model="sqlText">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-card>
  </div>
</template>

<script>
import { $FeatureApi } from "@/network/feature/FeatureApi";
import SideCategoryMenu from "@/components/feature/SideCategoryMenu";
import FeatureForm from "@/components/feature/FeatureForm";
import { $BasicTypeApi } from "@/network/feature/BasicTypeApi";
import { $FeatureFiledApi } from "@/network/feature/FeatureFieldApi";
import TreeSelect from "@/components/common/TreeSelect";
import BatchAddForm from "@/components/feature/BatchAddForm";

import '@/assets/css/featureLayout.css';
import { useFormDialog } from "@/components/formDialog/FormDialog";

export default {
  name: "BusinessFeatureManage",
  components: {
    SideCategoryMenu,
    FeatureForm,
    TreeSelect,
  },
  data() {
    return {
      breadcrumbItems: [],
      busiFeatureTreeData: [],
      curKind: '',        // 当前特征种类
      selectTreeNode: null,   // 当前选择的节点,
      tableEditMode: false,
      tableOper: "",
      //label: "1",
      featureFieldData: [
        // {name: 'doc_name', label: "文件名", kind: "basicType",  defaultValue: "-", isRef: 0, description: "文档名称"},
      ],  // 业务特征数据
      featureFieldItem: {
        name: "",
        typeId: "",
        defaultValue: "",
        isRef: "",
        description: ""
      },
      columns: [
        { prop: 'name', label: '名称', oper: false, editState: false },
        { prop: 'label', label: '显示名称', oper: false, editState: false },
        { prop: 'typeId', label: '基本类型', oper: false, editState: false },
        { prop: 'isRef', label: '是否引用', width: 80, oper: false, editState: false },
        { prop: 'defaultValue', label: '默认值', oper: false, editState: false },
        { prop: 'description', label: '描述', oper: false, editState: false },
        { label: '操作', oper: true, editState: false },
      ],
      basicTypeData: [],    // 基本类型数据
      // fieldAddWay: "single",    // 单个添加或者批量添加
      sqlText: "",
      activeName: "fieldList",

      featureForm: {
        type: 'feature',
        name: '',
        label: '',
        parentId: ''
      },
      batchAddFormData: {

      },
      checkedIds: [],

    }
  },

  methods: {
    // 业务特征树新增
    treeAddBtnClick() {
      if (this.selectTreeNode && this.selectTreeNode.type === 'feature') {
        this.$message.error("选择的节点为业务特征,不允许为其添加子节点！");
        return;
      }
      useFormDialog({
        title: "新增节点",
        parentLabel: this.selectTreeNode?.label,
        operType: 'add',
        type: 'feature',
      }, FeatureForm, async (data) => {
        data.parentId = this.selectTreeNode?.id;
        const res = await $FeatureApi.createBusiFeature(data);
        this.ShowMessage(res);
        this.loadBusiFeatureTreeData();
      }, () => { })
    },

    // 业务特征树删除
    treeDelBtnClick() {
      if (!this.selectTreeNode) {
        this.$message.info("请选择要删除的类型");
      } else {
        let msg = '确定删除选择的类型: ' + '"' + this.selectTreeNode.label + '"';
        this.$confirm(msg, "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await $FeatureApi.removeBusiFeature({ id: this.selectTreeNode.id });
          this.ShowMessage(res);
          await this.loadBusiFeatureTreeData();
        }).catch(err => {
          this.$message.info("取消操作!");
        })
      }
    },

    // 业务特征编辑
    treeEditBtnClick() {
      console.log("treeEditBtnClick > ", this.selectTreeNode);
      if (!this.selectTreeNode) {
        this.$message.error("请选择一个节点进行编辑");
        return;
      }
      this.featureForm = Object.assign(this.selectTreeNode);
      useFormDialog({
        title: "编辑",
        name: this.selectTreeNode.name,
        label: this.selectTreeNode.label,
        operType: "edit",
        type: this.selectTreeNode.type,
      }, FeatureForm, async (data) => {
        data.id = this.selectTreeNode.id;
        const res = await $FeatureApi.updateBusiFeature(data);
        this.ShowMessage(res);
        await this.loadBusiFeatureTreeData();
      }, () => { });
    },

    // 业务特征树点击
    treeNodeClickHandle(node) {
      let { id, name, label, parentId, type } = { ...node };
      this.selectTreeNode = { id, name, label, parentId, type };
      // console.log("当前选择的树节点: ", this.selectTreeNode);
      if (node.type && node.type === "feature") {
        this.loadFeatureFieldList(id);
      }
      if (this.activeName === "sqlPreview") {
        this.loadSQLText(id);
      }
    },

    // 业务特征树节点取消选中
    treeNodeCancelCheckHandler() {
      this.selectTreeNode = null;
    },

    /**
     * 加载业务特征树
     * @returns {Promise<void>}
     */
    async loadBusiFeatureTreeData() {
      let res = await $FeatureApi.getBusiFeatureTreeData({ label: "" });
      this.busiFeatureTreeData = res.data.dataList;
    },

    // 业务特征表单弹框点击确定
    async handleOkClick() {
      let data = { ...this.featureForm };
      debugger
      console.log(data);

      if (this.treeOper === "add" && this.selectTreeNode && this.selectTreeNode.type === "directory") {
        data.parentId = this.selectTreeNode.id;
      } else if (this.treeOper === "edit") {
        data.id = this.selectTreeNode.id;
      }
      let res = null;
      if (this.treeOper === "add") {
        res = await $FeatureApi.createBusiFeature(data);
      } else {
        res = await $FeatureApi.updateBusiFeature(data);
      }
      if (this.$ResHandler.isOk(res)) {
        this.$message.success(res.msg);
        await this.loadBusiFeatureTreeData();
      } else {
        this.$message.error(res.msg);
      }
    },

    handleCloseClick() {

    },

    // 业务对象保存字段
    async saveFeatureClick() {
      if (!this.tableEditMode) {
        return;
      }
      let featureId = this.selectTreeNode.id;
      // console.log([...this.featureFieldData]);
      let params = {
        featureId,
        fieldList: [...this.featureFieldData]
      }
      let res = await $FeatureFiledApi.batchSaveFiled(params);
      this.ShowMessage(res);
      await this.loadFeatureFieldList(featureId);
    },

    // 添加业务对象字段
    addFeatureFieldClick() {
      if (!this.isFeatureNode()) {
        this.$message.info("请选择一个业务对象");
        return;
      }
      let addItem = {
        isRef: 0,
        kind: "basicType",
        editState: true,
      }
      this.featureFieldData.push(addItem);
      this.tableEditMode = true;
      if (this.tableOper !== '') {
        this.tableOper = "addRow";    // 标记当前表格的操作为新增行
      }
    },

    // 批量添加业务对象字段
    batchAddFeatureFieldClick() {
      if (!this.isFeatureNode()) {
        this.$message.info("请选择一个业务对象");
        return;
      } else {
        this.batchAddFormData.selFeatureName = this.selectTreeNode.label + "(" + this.selectTreeNode.name + ")";
        this.batchAddFormData.selFeatureId = this.selectTreeNode.id;
      }
      this.tableEditMode = true;  // 开启表格编辑模式
      useFormDialog({
        title: '批量添加属性',
        formData: {
          selFeatureName: this.selectTreeNode.label + "(" + this.selectTreeNode.name + ")",
          selFeatureId: this.selectTreeNode.id,
        }
      }, BatchAddForm, async (data) => {
        let kind = data.kind;
        if (data.fieldList instanceof Array) {
          data.fieldList.forEach(item => {
            this.featureFieldData.push({
              name: item.name,
              label: item.label,
              typeId: item.basicTypeId,
              busiAttrId: item.id,
              typeLabel: item.basicTypeLabel,
              isRef: 0,
              kind,
              description: item.label,
            })
          });
        }

      }, () => { })

    },

    // 删除字段
    delFeatureClick() {
      let ids = [...this.checkedIds];
      if (!ids) {
        return;
      }
      this.$confirm('将删除已选择的字段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await $BusinessAttrApi.removeByIds({ ids });
        this.ShowMessage(res);
        await this.loadBusiAttrData(this.selectNode.id);
      }).catch(err => {
        this.$message.info("取消操作");
      })
    },

    // 表格选择行改变
    handleSelectionChange(rows) {
      this.checkedIds = rows.map(item => {
        return item.id;
      })
    },

    rowEditClick(row) {
      if (this.tableEditMode) {
        this.$message.info("请先保存当前编辑行!");
        return;
      }
      let id = row.id;
      let tar = this.featureFieldData.find(item => item.id === id);
      if (tar) {
        this.tableEditMode = true;
        Object.assign(this.featureFieldItem, tar);
        this.$set(tar, 'editState', true);
      }
    },

    rowDelClick(row) {
      console.log(row);

      if (!row || !row.id) {
        return;
      }
      //$FeatureFiledApi.removeByFieldIds({ ids: [row.id] })
      this.$confirm('将删除已选择的字段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await $FeatureFiledApi.removeByFieldIds({ ids: [row.id] });
        this.ShowMessage(res);
        this.loadFeatureFieldList(this.selectTreeNode.id);
      }).catch(err => {
        this.$message.info("取消操作");
      })




    },

    // 左侧树节点是否是业务特征
    isFeatureNode() {
      return this.selectTreeNode && this.selectTreeNode.type === 'feature';
    },

    // 加载基类型数据
    async loadBasicTypeData() {
      // debugger
      let res = await $BasicTypeApi.getBasicTypeTreeData();
      this.basicTypeData = res.data;
    },

    // 加载业务特征字段列表
    async loadFeatureFieldList(featureId) {
      this.tableEditMode = false;
      let res = await $FeatureFiledApi.listByFeatureId({ featureId })
      this.featureFieldData = res.data;
    },

    // 组件创建时加载首个业务特征的字段列表
    loadFeatureFieldListOnCreated() {
      let firstNode = this.busiFeatureTreeData[0];
      if (firstNode.type === 'feature') {
        this.loadFeatureFieldList(this.busiFeatureTreeData[0].id);
        this.selectTreeNode = firstNode;
      }
    },

    async loadSQLText(featureId) {
      let res = await $FeatureApi.getCreateTableSql({ featureId });
      if (this.$ResHandler.isOk(res)) {
        this.sqlText = res.data;
      } else {
        this.sqlText = res.msg;
      }
    },

    // 点击tab 页
    tabClickHandler(tab, e) {
      let featureId;
      if (this.selectTreeNode) {
        featureId = this.selectTreeNode.id;
      } else {
        featureId = this.busiFeatureTreeData[0].id;
      }
      if (tab.name === "sqlPreview") {
        this.loadSQLText(featureId);
      }
      this.activeName = tab.name;
    }
  },

  watch: {
    $route: {
      handler: function (newRoute, oldRoute) {
        this.breadcrumbItems = ['特征中心', newRoute.meta.description];
        this.curKind = newRoute.meta.name;
      },
      immediate: true,
      deep: true
    }
  },

  async created() {
    // debugger
    await this.loadBusiFeatureTreeData();
    await this.loadBasicTypeData();
    //this.loadFeatureFieldListOnCreated();
  }

}
</script>

<style scoped></style>